# coding=utf-8
from datetime import datetime

from flask import jsonify
from odps import ODPS

from blues.cloud import bp
from database2 import db_exec_many
from model.c_cloud import find_cloud_by_id
from model.c_department import get_depart_account_dict


def record_odps() -> bool:
    # odps 使用一级部门的ak才能访问具体的project
    account_dict = get_depart_account_dict()
    # 1 先使用云root ak sk，获取所有project和owner
    cloud = find_cloud_by_id(1)
    cloud_ep = cloud['odps_endpoint']
    root_odps = ODPS(cloud['root_access_key_id'], cloud['root_access_key_secret'], endpoint=cloud_ep)
    projects = root_odps.list_projects()

    # 将project 加入对应的账号字典下
    for p in projects:
        # print(p.name)
        # 排除系统project
        if 'ascm' not in str(p.owner):
            continue

        account_dict[str(p.owner).lstrip('ALIYUN$')]['odps_projects'].append(p.name)

    values_list = []
    # 遍历字典，对每个账号下的odps project，分别获取详细信息
    now = datetime.now()
    for i in account_dict.keys():
        depart_projects = account_dict[i]['odps_projects']
        if not depart_projects:
            continue
        ak = account_dict[i]['access_key_id']
        sk = account_dict[i]['access_key_secret']
        depart_id = account_dict[i]['department']
        depart_name = account_dict[i]['department_name']
        cloud_id = account_dict[i]['cloud_id']
        # 为一级部门创建一个odps客户端，然后查看他们的具体属性
        depart_odps = ODPS(ak, sk, endpoint=cloud_ep)
        for p_name in depart_projects:
            p1 = depart_odps.get_project(p_name)
            tmp_tuple = (
                p1.name, p1.extended_properties['usedQuotaPhysicalSize'],
                p1.extended_properties['maxQuotaPhysicalSize'],
                str(p1.owner).lstrip('ALIYUN$'), depart_id, depart_name, cloud_id, p1.creation_time, now
            )
            values_list.append(tmp_tuple)
    table = 'c_odps_info'
    fields = "project,used_size,max_size,owner,depart_id,depart_name,cloud_id,creation_time,record_time"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_odps_info', methods=['POST'])
def record_odps_api():
    success = record_odps()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
